package com.buddies.lottery.ui.lottery.trend;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseActivity;
import com.buddies.lottery.data.bean.Lottery;
import com.buddies.lottery.data.resp.LotteryTrendResponse;
import com.buddies.lottery.widget.TrendLoadMoreView;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.evrencoskun.tableview.TableView;
import com.evrencoskun.tableview.layoutmanager.CellLayoutManager;
import com.tencent.bugly.crashreport.BuglyLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LotteryTrendActivity extends BaseActivity<LotteryTrendContract.Presenter> implements LotteryTrendContract.View {

    private Lottery mLottery;

    private int page;

    private SwipeRefreshLayout mSwipeRefreshLayout;
    private TableView mTableView;
    private TrendLoadMoreView mLoadMoreView;
    private LotteryTrendAdapter mAdapter;

    private List<String> mColumnHeaderItems = new ArrayList<>();
    private List<String> mRowHeaderItems = new ArrayList<>();
    private List<List<String>> mCellItems = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_lottery_trend;
    }

    @Override
    protected void initView() {
        setUp();
        setTitle("基本走势");

        mTableView = findViewById(R.id.table_view);

        mSwipeRefreshLayout = findViewById(R.id.refresher);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                forceRefresh();
            }
        });

        View loadingLayout = findViewById(R.id.loading_layout);
        loadingLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLoadMore();
            }
        });

        mLoadMoreView = new TrendLoadMoreView();
        mLoadMoreView.bind(loadingLayout);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            mLottery = (Lottery) intent.getSerializableExtra("lottery");
        }

        mPresenter = new LotteryTrendPresenter(this);

//        mColumnHeaderItems.add("期号");
//        mColumnHeaderItems.add("总和");
//        mColumnHeaderItems.add("大");
//        mColumnHeaderItems.add("小");
//        mColumnHeaderItems.add("单");
//        mColumnHeaderItems.add("双");

        mAdapter = new LotteryTrendAdapter(this);
        mTableView.setAdapter(mAdapter);
        mAdapter.setAllItems(mColumnHeaderItems, mRowHeaderItems, mCellItems);
        mTableView.getCellRecyclerView().addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                CellLayoutManager cellLayoutManager = mTableView.getCellLayoutManager();
                int firstPosition = cellLayoutManager.findFirstCompletelyVisibleItemPosition();
                BuglyLog.e(TAG, "onScrolled dx:" + dx + ", dy:" + dy + ", visiblePos:" + firstPosition + ", status:" + mLoadMoreView.getLoadMoreStatus());

                mSwipeRefreshLayout.setEnabled(firstPosition == 0);

                if (mLoadMoreView.getLoadMoreStatus() != LoadMoreView.STATUS_LOADING && dy > 0) {

                    int childCount = cellLayoutManager.getChildCount();
                    int itemCount = cellLayoutManager.getItemCount();

                    BuglyLog.e(TAG, "load more firstPosition + childCount:" + (firstPosition + childCount) + ", itemCount:" + itemCount);

                    if (firstPosition + childCount >= itemCount - 1) {
                        onLoadMore();
                    }
                }
            }
        });

        forceRefresh();
    }

    private void onLoadMore() {
        mLoadMoreView.loadMoreLoading();
        page++;
        onLoadData(page);
    }

    protected void forceRefresh() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(true);
                    page = 1;
                    onLoadData(page);
                }
            });
        }
    }

    protected void onLoadData(int page) {
        Map<String, Object> params = new HashMap<>();
        params.put("lotteryId", mLottery.id);

        mPresenter.onLoadData(params, page);
    }

    public void onDataLoaded(LotteryTrendResponse response) {
        mSwipeRefreshLayout.setRefreshing(false);

        if (page == 1) {
            mColumnHeaderItems.clear();
            mRowHeaderItems.clear();
            mCellItems.clear();
        }

        List<String> columnHeaders = response.column_headers;
        if (columnHeaders != null && !columnHeaders.isEmpty()) {
            mColumnHeaderItems.clear();
            mColumnHeaderItems.addAll(columnHeaders);
        }

        List<String> rowHeaders = response.row_headers;
        if (rowHeaders != null && !rowHeaders.isEmpty()) {
            mRowHeaderItems.addAll(rowHeaders);
        }

        List<List<String>> cells = response.cells;
        if (cells != null && !cells.isEmpty()) {
            mCellItems.addAll(cells);
            mLoadMoreView.loadMoreComplete();
        } else {
            mLoadMoreView.loadMoreEnd();
        }
        mAdapter.setAllItems(mColumnHeaderItems, mRowHeaderItems, mCellItems);
//        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        mSwipeRefreshLayout.setRefreshing(false);
        mLoadMoreView.loadMoreFail();
        page --;
    }

    public static void launch(Context context, Lottery lottery) {
        Intent intent = new Intent(context, LotteryTrendActivity.class);
        intent.putExtra("lottery", lottery);
        context.startActivity(intent);
    }

}
